package com.edu.chapter07.network;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelper {
    private static Retrofit retrofitInstance;

    // 获取 Retrofit 实例（线程安全）
    private static synchronized Retrofit getRetrofit() {
        if (retrofitInstance == null) {
            // 创建 OkHttp 客户端（可添加拦截器）
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)) // 日志
                    .connectTimeout(30, TimeUnit.SECONDS) // 超时设置
                    .build();

            // 构建 Retrofit
            retrofitInstance = new Retrofit.Builder()
                    .baseUrl("https://jsonplaceholder.typicode.com/") // 基础 URL
                    .client(okHttpClient) // 绑定 OkHttp
                    .addConverterFactory(GsonConverterFactory.create()) // JSON 自动解析
                    .build();
        }
        return retrofitInstance;
    }

    // 获取 API 服务实例
    public static ApiService getApiService() {
        return getRetrofit().create(ApiService.class);
    }
}